﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Golos.BackEnd.Client;

namespace Golos.Users.UserCache
{
	public partial class Cache
	{
        public Guid RegisterUser(string name, string email, UserIdType userIdType, string identificationId)
        {
            Guid? userIdExist = GetUserId(userIdType, identificationId);
            if (userIdExist!=null)
                return userIdExist.Value;
            Guid newUserId = Guid.NewGuid();
            UserInfo newUser = new UserInfo(newUserId, name, email, userIdType, identificationId);
            lock (users)
            {
                if (!FlushNewUserToDb(newUserId, name, email, userIdType, identificationId, true))
                    throw new Exception("Can't register user");
                users.Add(newUserId, newUser);
                return newUserId;
            }
        }

	    public void AttachUserIdentification(Guid userId, UserIdType idType, string indId, bool saveActivityToSocialWeb)
	    {
	        lock (users)
	        {
                List<Guid> foundUsers = new List<Guid>();
	            foreach (Guid uId in users.Keys)
	            {
                    if(userId == uId)
                        continue;
                    if (!users[uId].UserIdentification.ContainsKey(idType))
                        continue;
                    if (users[uId].UserIdentification[idType] != indId)
                        continue;
	                foundUsers.Add(uId);
	            }
                UserInfo userInfo = users[userId];
                PollsClient client = new PollsClient();
	            if(!client.MergeUserAnswer(userId, foundUsers))
                    throw new Exception("Can't attach user identification");
                if(!SaveUserIdentificationToDb(userId, idType, indId, saveActivityToSocialWeb, foundUsers))
                    throw new Exception("Can't attach user identification");
                userInfo.AttachUserIdentification(idType, indId);
	            foreach (Guid foundUser in foundUsers)
	            {
	                users.Remove(foundUser);
	            }
	        }
	        
	    }

	    public void UpdateProfile(UserInfo userInfo)
	    {
            lock (users)
            {
                if (!users.ContainsKey(userInfo.Id))
                    throw new Exception("Can't update profile. User not found");
                if(!UpdateProfileInDb(userInfo))
                    throw new Exception("Can't update profile");
                users[userInfo.Id] = userInfo;
            }
	    }
	}
}
